package com.boby.homecamera.util;
import android.os.StatFs;
import android.content.Context;
import android.os.Environment;

import androidx.core.content.ContextCompat;

import java.io.File;

public class StorageUtil {

    public static long getAvailableExternalStorage(Context context) {
        long availableBytes = 0;

//        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { // API 24+
//            StorageManager storageManager = (StorageManager) context.getSystemService(Context.STORAGE_SERVICE);
//            for (StorageVolume volume : storageManager.getStorageVolumes()) {
//                if (volume.isRemovable()) {
//                    File path = null;
//                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
//                        path = volume.getDirectory();
//                    }else {
//
//                    }
//                    if (path != null && path.canRead()) {
//                        StatFs stat = new StatFs(path.getPath());
//                        availableBytes = stat.getAvailableBytes();
//                        break;
//                    }
//                }
//            }
//        } else {
            String state = Environment.getExternalStorageState();
            if (Environment.MEDIA_MOUNTED.equals(state)) {
                File path = Environment.getExternalStorageDirectory();
                if (path != null && path.canRead()) {
                    StatFs stat = new StatFs(path.getPath());
                    availableBytes = stat.getAvailableBlocksLong() * stat.getBlockSizeLong();
                }
            }
//        }

        return availableBytes;
    }
    public static long getRemovableStorageAvailable(Context context) {
        File[] externalDirs = ContextCompat.getExternalFilesDirs(context, null);
        for (File file : externalDirs) {
            if (file != null) {
                // 判断是否是可移除设备（通常是 SD 卡）
                if (Environment.isExternalStorageRemovable(file)) {
                    StatFs stat = new StatFs(file.getAbsolutePath());
                    return stat.getAvailableBytes();
                }
            }
        }
        return 0;
    }

}
